<?php

namespace tmcore\services\crud\generators;

use tmcore\services\crud\UtilService;

class VueDetailView extends Generate
{
    /**
     * @var string
     */
    protected string $fileType = 'vue';

    /**
     * 替换变量
     */
    public function replaceContent()
    {
        $search = [
            '{TEMPLATE_HEADER}',
            '{DESC_VIEW}',
            '{TEMPLATE_FOOTER}',
            '{CAMEL_CLASS_NAME}',
            '{JS_USE}',
            '{JS_HEADER}',
            '{PK}',
            '{JS_FOOTER}',
            '{JS_EMIT}',
            '{JS_EXPOSE}'
        ];

        $replace = [
            $this->getTemplateHeaderContent(),
            $this->getDescViewContent(),
            $this->getTemplateFooterContent(),
            UtilService::lcfirst($this->getCamelClassName()),
            $this->getJsUseContent(),
            $this->getJsHeaderContent(),
            $this->getPk(),
            $this->getJsFooterContent(),
            $this->getJsEmitContent(),
            $this->getJsExposeContent()
        ];

        $content = UtilService::replaceFileContent($search, $replace, $this->getStub('edit'));

        $this->setContent($content);
    }

    /**
     * 返回模板路径
     * @param string $type
     * @return mixed|string|string[]
     */
    public function getStub(string $type = 'edit')
    {
        $basePath = 'vue/views/';

        $stubs = [
            'description_areaSelect' => $this->getTplPath($basePath . 'description/areaSelect'),
            'description_checkbox' => $this->getTplPath($basePath . 'description/checkbox'),
            'description_datePicker' => $this->getTplPath($basePath . 'description/datePicker'),
            'description_default' => $this->getTplPath($basePath . 'description/default'),
            'description_number' => $this->getTplPath($basePath . 'description/number'),
            'description_fileSelect' => $this->getTplPath($basePath . 'description/fileSelect'),
            'description_fileSelectMul' => $this->getTplPath($basePath . 'description/fileSelectMul'),
            'description_imageSelect' => $this->getTplPath($basePath . 'description/imageSelect'),
            'description_imageSelectMul' => $this->getTplPath($basePath . 'description/imageSelectMul'),
            'description_radio' => $this->getTplPath($basePath . 'description/radio'),
            'description_select' => $this->getTplPath($basePath . 'description/select'),
            'description_selectMul' => $this->getTplPath($basePath . 'description/selectMul'),
            'description_videoSelect' => $this->getTplPath($basePath . 'description/videoSelect'),
            'description_videoSelectMul' => $this->getTplPath($basePath . 'description/videoSelectMul'),
            'description_userSelect' => $this->getTplPath($basePath . 'description/userSelect'),
            'description_timePicker' => $this->getTplPath($basePath . 'description/timePicker'),
            'page_templateHeaderDialog' => $this->getTplPath($basePath . 'page/detail/templateHeaderDialog'),
            'page_templateFooterDialog' => $this->getTplPath($basePath . 'page/detail/templateFooterDialog'),
            'page_templateHeaderPage' => $this->getTplPath($basePath . 'page/detail/templateHeaderPage'),
            'page_templateFooterPage' => $this->getTplPath($basePath . 'page/detail/templateFooterPage'),
            'page_templateHeaderDrawer' => $this->getTplPath($basePath . 'page/detail/templateHeaderDrawer'),
            'page_templateFooterDrawer' => $this->getTplPath($basePath . 'page/detail/templateFooterDrawer'),
            'edit' => $this->getTplPath($basePath . 'detail'),
        ];

        return $type ? $stubs[$type] : $stubs;
    }

    /**
     * 设置文件路径
     */
    public function setFilePath()
    {
        $name = 'detail.' . $this->fileType;
        $this->setCrudFileName($name);

        $module_path = dirname($this->rootPath) . '/admin/src/views/';
        if (!empty($this->classDir)) $module_path .= $this->classDir . '/';
        $module_path .= UtilService::lcfirst($this->getCamelClassName()) . '/component/';
        $this->setCrudModuleFilePath($module_path);

        $data_path = $this->crudDir . 'vue/src/views/';
        if (!empty($this->classDir)) $data_path .= $this->classDir . '/';
        $data_path .= UtilService::lcfirst($this->getCamelClassName()) . '/component/';
        $this->setCrudDataFilePath($data_path);
    }

    /**
     * 获取模板顶部
     * @return string
     */
    public function getTemplateHeaderContent()
    {
        $tpl_arr = ['Dialog', 'Page', 'Drawer'];
        return file_get_contents($this->getStub('page_templateHeader' . $tpl_arr[($this->crudData['component_type'] - 1)]));
    }

    /**
     * 获取表单内容
     * @return string
     */
    public function getDescViewContent()
    {
        $content = '';
        $form_type_arr = ['fileSelect', 'imageSelect', 'videoSelect', 'select'];
        foreach ($this->crudColumn as $key=>$value) {
            if($value['is_detail']) {

                $search = [
                    '{COLUMN_COMMENT}',
                    '{COLUMN_NAME}',
                    '{COLUMN_NAME_DESC}',
                ];

                $replace = [
                    $this->getTableColumnComment($value['column_comment']),
                    $value['column_name'],
                    $value['column_name'] . '_' . UtilService::lower($this->attrPrefix),
                ];

                $tableStubType = $value['view_type'];

                if ($value['view_type'] == 'input' || $value['view_type'] == 'number' || $value['view_type'] == 'textarea' || $value['view_type'] == 'editor' || $value['view_type'] == 'treeSelect') {
                    $tableStubType = 'default';
                    if($value['column_type'] == 'decimal') $tableStubType = 'number';
                }

                if(in_array($tableStubType, $form_type_arr) && !empty($value['extra']['multiple'])) {
                    $tableStubType .= 'Mul';
                }

                $content .= UtilService::replaceFileContent($search, $replace, $this->getStub('description_' . $tableStubType)) . PHP_EOL;

            }
        }
        if (!empty($content)) {
            $content = substr($content, 0, -1);
        }
        return UtilService::setBlankSpace($content, '            ');
    }

    /**
     * 获取模板底部
     * @return false|string
     */
    public function getTemplateFooterContent()
    {
        $tpl_arr = ['Dialog', 'Page', 'Drawer'];
        return file_get_contents($this->getStub('page_templateFooter' . $tpl_arr[($this->crudData['component_type'] - 1)]));
    }

    /**
     * 获取JS_USE内容
     * @return string
     */
    public function getJsUseContent()
    {
        $content = '';

        // 工具函数调用
        if (!empty($this->params['crud_column_check']['is_detail_datePicker']) || !empty($this->params['crud_column_check']['is_detail_imageSelect'])) {
            $funContent = '{ ';
            if(!empty($this->params['crud_column_check']['is_detail_imageSelect'])) $funContent .= 'getUrl, ';
            if(!empty($this->params['crud_column_check']['is_detail_datePicker'])) $funContent .= 'dateToString, isNumber, ';
            $funContent = substr($funContent, 0, -2);
            $funContent .= ' }';

            $content .= <<<CONTENT
import $funContent from '/@/utils/util';
CONTENT . PHP_EOL;
        }

        // 路由跳转函数
        if ($this->crudData['component_type'] == 2) {
            $content .= <<<CONTENT
import { useRoute } from 'vue-router';
CONTENT. PHP_EOL;
        }

        // 拼接api调用
        $apiClass = UtilService::lcfirst($this->crudData['class_name']);

        $apiContent = '{ ' . $apiClass . 'Detail }';

        $apiDir = UtilService::lower($this->classDir) . ($this->classDir ? '/' : '') . UtilService::lcfirst($this->crudData['class_name']);

        $content .= <<<CONTENT
import {$apiContent} from '/@/api/{$apiDir}';
CONTENT;

        return $content;
    }

    /**
     * 获取JS_HEADER内容
     * @return string
     */
    public function getJsHeaderContent()
    {
        $content = '';

        $tpl_arr = ['dialog', 'page', 'drawer'];
        $tpl_type = $tpl_arr[($this->crudData['component_type'] - 1)];

        // 检测模态框或抽屉
        if ($this->crudData['component_type'] == 1 || $this->crudData['component_type'] == 3) {
            $content .= <<<CONTENT
const {$tpl_type}Ref = ref(null);
CONTENT. PHP_EOL . PHP_EOL;
        }

        $title_content = "'{$this->crudData['table_comment']}详情';";
        $tab1 = UtilService::tab(1);

        //拼接标题
        $content .= <<<CONTENT
const {$tpl_type}Title = computed(() => {
{$tab1}return {$title_content}
});
CONTENT. PHP_EOL . PHP_EOL;

        // 路由函数
        if($this->crudData['component_type'] == 2) {
            $content .= <<<CONTENT
const route = useRoute();
CONTENT . PHP_EOL . PHP_EOL;
        }

        // 检测模态框或抽屉
        if ($this->crudData['component_type'] == 1 || $this->crudData['component_type'] == 3) {
            $content .= <<<CONTENT
const emit = defineEmits(['close']);
CONTENT. PHP_EOL . PHP_EOL;
        }

        $content = substr($content, 0, -2);

        return $content;
    }

    /**
     * 获取JS_EMIT内容
     * @return string
     */
    public function getJsEmitContent() {
        $content = '';

        $tpl_arr = ['dialog', 'page', 'drawer'];
        $tpl_type = $tpl_arr[($this->crudData['component_type'] - 1)];
        if ($this->crudData['component_type'] == 1 || $this->crudData['component_type'] == 3) {
            $content .= PHP_EOL;
            $content .= <<<CONTENT
const handleClose = () => {
	emit('close');
};

const open = () => {
	{$tpl_type}Ref.value?.open();
};
CONTENT. PHP_EOL;
        }

return $content;
    }

    /**
     * 获取JS_EXPOSE内容
     * @return string
     */
    public function getJsExposeContent() {
        $content = '';

        if ($this->crudData['component_type'] == 1 || $this->crudData['component_type'] == 3) {
            $content .= PHP_EOL;
            $content .= <<<CONTENT
defineExpose({
	open,
	setFormData,
});
CONTENT. PHP_EOL;
        }

        return $content;
    }

    /**
     * 获取JS_FOOTER内容
     * @return string
     */
    public function getJsFooterContent() {
        $content = '';
        $tab1 = UtilService::tab(1);
        if($this->crudData['component_type'] == 2) {
            $content .= <<<CONTENT
{$tab1}if (route.query.id) {
{$tab1}    setFormData({{$this->getPk()}:route.query.{$this->getPk()}}, null);
{$tab1}}
CONTENT;
        }

        return $content;
    }

}